package cn.zhoujing.ssedemo.controller;

import cn.zhoujing.ssedemo.dto.SendMegRequest;
import cn.zhoujing.ssedemo.service.SseService;
import cn.zhoujing.ssedemo.service.impl.SseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

/**
 * @author zhoujing
 * @createTime 2023/9/18 - 0:53
 */
@RestController
@RequestMapping("/sse")
@CrossOrigin
public class SseController {

    @Autowired
    private SseService sseServer;


    @GetMapping(value = "/subscribe/{userId}")
    public SseEmitter subscribe(@PathVariable("userId") String userId){
        return sseServer.connect(userId);
    }


    @PostMapping(value = "/send/{userId}")
    public String sendMessage(@PathVariable("userId") String userId ,@RequestBody SendMegRequest sendMegRequest){
        if(sseServer.send(sendMegRequest.getUserId(), sendMegRequest.getContent())){
            return "Success";
        }
        return "Faild";
    }

    @GetMapping(value = "/close/{userId}")
    public void close(@PathVariable("userId") String userId){
        sseServer.close(userId);
    }

}
